//
//  MHCircleMemberViewController.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/4/28.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHCircleMemberViewController.h"
#import "MHCommonCell.h"
#import "MHAlertTableViewView.h"
#import "MHAlertTableViewModel.h"
#import "MHCircleMemberViewModel.h"
#import "MHSearchBar.h"
#import "MHSearchMembersViewModel.h"
#import "MHMomentViewModel.h"
#import "MHSearchMembersViewController.h"

@interface MHCircleMemberViewController ()<UISearchResultsUpdating,UISearchControllerDelegate,UISearchBarDelegate>
@property (nonatomic,strong) MHCircleMemberViewModel *viewModel;
@property (nonatomic, readwrite, strong) UISearchController *searchController;
@property (nonatomic, readwrite, assign) UIStatusBarStyle style;
@property (nonatomic, readwrite, strong) MHSearchMembersViewController *resultController;
@property(nonatomic, strong) UISearchBar *searhBar;


@end

@implementation MHCircleMemberViewController

@dynamic viewModel;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.searhBar =  [[MHSearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 44)];
    self.tableView.tableHeaderView = self.searhBar;
    self.searhBar.delegate = self;
    UITextField *txfSearchField = [self.searhBar valueForKey:@"_searchField"];
    [txfSearchField setBackgroundColor:RGBA(237, 238, 239, 1)];
    [self _setup];
    [self _setupSubViews];
}


- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar;
{
    self.searchController.active = YES;
    return YES;
}


#pragma mark - Override
- (void)bindViewModel{
    [super bindViewModel];
    
    //    [UINavigationBar appearance].shadowImage = [UIImage new];
    //    [[UINavigationBar appearance] setBackgroundImage:[UIImage new] forBarMetrics:0];
    //    UINavigationBar.appearance().shadowImage =
    //    UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
    /// 监听searchVc的活跃度
    [RACObserve(self, searchController.active)
     subscribeNext:^(NSNumber * active) {
         NSLog(@"active is %zd",active.boolValue);
         
         
     }];
    
}

- (void)_setupSubViews{
    MHSearchMembersViewModel *viewModel = [[MHSearchMembersViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelUtilKey:self.viewModel.info}];
    MHSearchMembersViewController *resultController = [[MHSearchMembersViewController alloc] initWithViewModel:viewModel];
    self.resultController = resultController;
    
    /// 搜索vc
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:resultController];
    // 设置结果更新代理
    self.searchController.searchResultsUpdater = resultController;
    self.searchController.searchBar.translucent = YES;
    // 因为在当前控制器展示结果, 所以不需要这个透明视图
    
    self.searchController.searchBar.backgroundImage = [UIImage new];
    //    self.searchController.searchBar.barTintColor = UIColor.redColor()
    //    self.searchController.searchBar.tintColor = UIColor.whiteColor()
    
    
    self.searchController.dimsBackgroundDuringPresentation = YES;
    // 是否自动隐藏导航
    self.searchController.hidesNavigationBarDuringPresentation = YES;
    self.searchController.delegate = self;
    
    UISearchBar *searchBar = self.searchController.searchBar;
    //    searchBar.barStyle = UIBarStyleDefault;
    searchBar.searchBarStyle = UISearchBarStyleProminent;
    searchBar.placeholder = @"搜索";
    searchBar.translucent = YES;
    //    UIOffset offset = {10.0,0};
    //    _searchController.searchBar.searchTextPositionAdjustment = offset;
    //    searchBar.barTintColor = MHColorFromHexString(@"#EFEFF4");
    //
    //    [searchBar setImage:[UIImage imageNamed:@"VoiceSearchStartBtn"] forSearchBarIcon:UISearchBarIconBookmark state:UIControlStateNormal];
    /// 设置代理
    searchBar.delegate = self.resultController;
    CGRect rect = searchBar.frame;
    rect.size.height = 44;
    //    rect.origin.y += 10;
    searchBar.frame = rect;
    searchBar.barTintColor = MH_MAIN_BACKGROUNDCOLOR;
    
    UITextField *txfSearchField = [searchBar valueForKey:@"_searchField"];
    [txfSearchField setBackgroundColor:RGBA(237, 238, 239, 1)];
    
//    [txfSearchField setLeftView:UITextFieldViewModeNever];
//    [txfSearchField setBorderStyle:UITextBorderStyleRoundedRect];
//    txfSearchField.layer.borderWidth = 8.0f;
//    txfSearchField.layer.cornerRadius = 10.0f;
//    txfSearchField.layer.borderColor = [UIColor clearColor].CGColor;
    
//    searchBar.tintColor = [UIColor colorWithRed:0 green:(190 / 255.0) blue:(12 / 255.0) alpha:1];
//    UITextField *textField = (UITextField *)[self mrc_subviewPassingTest:^(UIView *subview) {
//        if ([NSStringFromClass(subview.class) hasSuffix:@"TextField"]) {
//            return YES;
//        }
//        return NO;
//    }];
//    textField.layer.cornerRadius = 18.0f;
//    textField.backgroundColor = RGBA(237, 238, 239, 1);
//    textField.masksToBounds = YES;
    
//    self.searhBar.backgroundColor = RGBA(237, 238, 239, 1);
    
    
    [self.searhBar setBackgroundImage:[UIImage new]];
    [self.searchController.searchBar setBackgroundImage:[UIImage new]];
    self.searhBar.searchBarStyle = UISearchBarStyleProminent;
    [self.searhBar insertSubview:searchBar atIndex:0];
    [_searchController.searchBar sizeToFit];
    /// 设置frame
    
    //    self.searhBar.barTintColor = MH_MAIN_BACKGROUNDCOLOR; //MH_MAIN_BACKGROUNDCOLOR;
    
    
    //    UIImageView *bgView = [[[searchBar.subviews objectAtIndex:0] subviews] firstObject];
    //    bgView.layer.borderColor = MHColorFromHexString(@"#DFDFDD").CGColor;
    //    bgView.layer.borderWidth = 1;
    
    // 1. 创建磨砂视图
    // 判断系统版本是否支持 8.0
    UIView *blurEffectView;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        // 磨砂效果
        UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
        // 磨砂视图
        blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    } else {
        // 屏幕截图 - 调用苹果官方框架实现磨砂效果
        UIImage *screenShot = [UIImage mh_screenShot].applyLightEffect;
        blurEffectView = [[UIImageView alloc] initWithImage:screenShot];
    }
    /// 切记： 将磨砂视图 插入到最底层
    [self.searchController.view insertSubview:blurEffectView atIndex:0];
    [blurEffectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.searchController.view);
    }];
    
    /// 设置当前Controller的definesPresentationContext为YES，表示UISearchController在present时，可以覆盖当前controller。
    self.definesPresentationContext = YES;
}

- (void)_setup{
    //    self.style = UIStatusBarStyleLightContent;
    [self setNeedsStatusBarAppearanceUpdate];
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return self.style;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }else
    {
        return  [super tableView:tableView heightForHeaderInSection:section];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}
-(UIEdgeInsets)contentInset
{
    return isIPhoneX() ? UIEdgeInsetsMake(112, 0, 0, 0) : UIEdgeInsetsMake(76, 0, 0, 0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath{
    MHCommonCell *cell =  [MHCommonCell cellWithTableView:tableView];
    cell.avatarView.contentMode = UIViewContentModeScaleAspectFit;
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
    MHCommonGroupViewModel *groupViewModel = self.viewModel.dataSource[indexPath.section];
    id object = groupViewModel.itemViewModels[indexPath.row];
//    MHCommonItemViewModel *itemItemViewModel =  (MHCommonItemViewModel *)object;
    MHCommonItemViewModel *model =  (MHCommonItemViewModel *)object;
    MHCircleMember *circleMember = (MHCircleMember *)model.model;
    if(self.viewModel.info.identType == MHCircleIdentityTypeOwner || self.viewModel.info.identType == MHCircleIdentityTypeManager)
    {
        MHAlertTableViewModel *settingManage = [MHAlertTableViewModel new];
        BOOL isManager =  (circleMember.identType == MHCircleIdentityTypeManager);
        BOOL notSelf =  (circleMember.identType == MHCircleIdentityTypeOwner);
        settingManage.titile = isManager ? @"取消管理员" : @"设置成管理员";
        __weak __typeof(self)weakSelf = self;
        settingManage.operationBlock = ^{
            //            MHCommonGroupViewModel *groupViewModel = self.viewModel.dataSource[cell.tag];
            //            id object = groupViewModel.itemViewModels[cell.imageView.tag];
            //            MHCommonItemViewModel *itemItemViewModel =  (MHCommonItemViewModel *)object;
            //            MHCircleMember *circleMember = (MHCircleMember *)itemItemViewModel.model;
            if(isManager)
            {
                [[weakSelf.viewModel.cancelMemberTypeCommand execute:@(circleMember.autoId)] subscribeNext:^(id x) {
                    circleMember.identType = MHCircleIdentityTypeGuestMember;
                    [self.viewModel willChangeValueForKey:@"circleMembers"];
                    [self.viewModel didChangeValueForKey:@"circleMembers"];
                }];
            }else
            {
                
                [[weakSelf.viewModel.setIdentityCommand execute:@{@"memberId":@(circleMember.autoId),@"identType":@(2)}] subscribeNext:^(id x) {
                    circleMember.identType = MHCircleIdentityTypeManager;
                    [self.viewModel willChangeValueForKey:@"circleMembers"];
                    [self.viewModel didChangeValueForKey:@"circleMembers"];
                }];
            }
            
            [weakSelf.zh_popupController dismiss];
        };
        
        MHAlertTableViewModel *settingjb = [MHAlertTableViewModel new];
        BOOL isInterviewer =  (circleMember.identType == MHCircleIdentityTypeGuest);
        settingjb.titile = isInterviewer ? @"取消嘉宾":@"设为嘉宾";
        settingjb.operationBlock = ^{
            if(isInterviewer)
            {
                [[weakSelf.viewModel.cancelMemberTypeCommand execute:@(circleMember.autoId)] subscribeNext:^(id x) {
                    circleMember.identType = MHCircleIdentityTypeGuestMember;
                    [self.viewModel willChangeValueForKey:@"circleMembers"];
                    [self.viewModel didChangeValueForKey:@"circleMembers"];
                }];
            }else
            {
                [[weakSelf.viewModel.setIdentityCommand execute:@{@"memberId":@(circleMember.autoId),@"identType":@(3)}] subscribeNext:^(id x) {
                    circleMember.identType = MHCircleIdentityTypeGuest;
                    [self.viewModel willChangeValueForKey:@"circleMembers"];
                    [self.viewModel didChangeValueForKey:@"circleMembers"];
                }];
            }
            
            [weakSelf.zh_popupController dismiss];
        };
        MHAlertTableViewModel *black = [MHAlertTableViewModel new];
        black.titile = @"拉黑";
        @weakify(self);
        black.operationBlock = ^{
            @strongify(self);
            
            [self showAlertViewControllerWithTitle:[NSString stringWithFormat:@"确定将 %@ 拉黑",circleMember.nickName] content:@"拉黑后,该成员将无法查看圈内消息以及发表内容" comfirmblock:^{
                [[weakSelf.viewModel.blakMemberCommand execute:@(circleMember.userId)] subscribeNext:^(id x) {
                    [self.viewModel.circleMembers removeObject:circleMember];
                    [self.viewModel willChangeValueForKey:@"circleMembers"];
                    [self.viewModel didChangeValueForKey:@"circleMembers"];
                }];
                [weakSelf.zh_popupController dismiss];
            } dissMissBlock:^{
                [weakSelf.zh_popupController dismiss];
            }];
            
        };
        
        MHAlertTableViewModel *remove = [MHAlertTableViewModel new];
        remove.titile = @"移除该成员";
        remove.operationBlock = ^{
            [self showAlertViewControllerWithTitle:@"移除该成员" content:@"确定移除该成员?" comfirmblock:^{
                [weakSelf.viewModel.removeMemberCommand execute:@(circleMember.autoId)];
                [weakSelf.zh_popupController dismiss];
                [self.viewModel.circleMembers removeObject:circleMember];
                [self.viewModel willChangeValueForKey:@"circleMembers"];
                [self.viewModel didChangeValueForKey:@"circleMembers"];
            }dissMissBlock:^{
                [weakSelf.zh_popupController dismiss];
            }];
            
        };
        
        
        if (indexPath.section == 1 && !notSelf) {
//            model.operation = ^{
                if (self.viewModel.info.identType == MHCircleIdentityTypeOwner) {
                    NSMutableArray *operationPermisson = [@[settingManage,black,remove] mutableCopy];
                    if (isInterviewer) {
                        [operationPermisson insertObject:settingjb atIndex:0];
                    }
                    MHAlertTableViewView *tableView  = [[MHAlertTableViewView alloc] initWithDataSource:operationPermisson andHeaderData:circleMember];
                    tableView.width = self.view.width * 0.8;
                    weakSelf.zh_popupController = [zhPopupController new];
                    [weakSelf.zh_popupController presentContentView:tableView];
                }
//            };
        }else if (indexPath.section == 2)
        {
//            model.operation = ^{
                NSMutableArray *array = [@[] mutableCopy];
                //                BOOL isManager = (self.viewModel.info.identType == MHCircleIdentityTypeOwner || self.viewModel.info.identType == MHCircleIdentityTypeManager);
                //                isManager
                self.viewModel.info.identType == MHCircleIdentityTypeOwner ? ([array appendObjects: @[settingManage,black]] ) : ([array appendObjects:@[black]]);
                if (isInterviewer) {
                    [array appendObject:settingjb];
                }
                [array appendObject:remove];
                MHAlertTableViewView *tableView  = [[MHAlertTableViewView alloc] initWithDataSource:array andHeaderData:circleMember];
                tableView.width = self.view.width * 0.8;
                weakSelf.zh_popupController = [zhPopupController new];
                [weakSelf.zh_popupController presentContentView:tableView];
//            };
        }
    }
}

- (void)configureCell:(MHCommonCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(id)object{
    MHCommonItemViewModel *model =  (MHCommonItemViewModel *)object;
    MHCircleMember *circleMember = (MHCircleMember *)model.model;
    cell.imageView.userInteractionEnabled = YES;
    cell.tag = indexPath.section;
    cell.imageView.tag = indexPath.row;
    @weakify(self);
    [cell.imageView bk_whenTapped:^{
        @strongify(self);
        MHCommonGroupViewModel *groupViewModel = self.viewModel.dataSource[cell.tag];
        id object = groupViewModel.itemViewModels[cell.imageView.tag];
        MHCommonItemViewModel *itemItemViewModel =  (MHCommonItemViewModel *)object;
        MHCircleMember *userMember = (MHCircleMember *)itemItemViewModel.model;
        if (![userMember isKindOfClass:[MHCircleMember class]]) {
            return ;
        }
        IMAUser *user = [[IMAUser alloc] initWith:[NSString stringWithFormat:@"%d",userMember.userId]];
        user.icon = userMember.fullUserFace;
        user.nickName = userMember.nickName;
        IMAConversation *conversation =  [[IMAPlatform sharedInstance].conversationMgr chatWith:user];
        MHMomentViewModel *viewModel = [[MHMomentViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelIsFootPrint:@(true),MHViewModelTitleKey:isEquaalCurrentUserId(user.userId)?@"我的足迹":@"Ta的足迹",MHViewModelConversation:conversation}];
        viewModel.userId = [user.userId intValue];
        viewModel.imUser = user;
        [self.viewModel.services pushViewModel:viewModel animated:YES];
    }];
    
    [cell bindViewModel:object];
}


- (void)willPresentSearchController:(UISearchController *)searchController{
    MHLogFunc;
    /// 取消侧滑功能
    self.viewModel.interactivePopDisabled = YES;
}
- (void)didPresentSearchController:(UISearchController *)searchController{
    MHLogFunc;
    self.style = UIStatusBarStyleDefault;
    [self setNeedsStatusBarAppearanceUpdate];
    /// 键盘弹起
    [self.searchController.searchBar becomeFirstResponder];
}
- (void)willDismissSearchController:(UISearchController *)seaxrchController{
    /// 回复侧滑功能
    self.viewModel.interactivePopDisabled = NO;
    MHLogFunc;
}
- (void)didDismissSearchController:(UISearchController *)searchController{
    MHLogFunc;
    self.style = UIStatusBarStyleLightContent;
    [self setNeedsStatusBarAppearanceUpdate];
    
    CGRect rect = self.searchController.searchBar.frame;
//    rect = CGRectMake(0, 0, self.view.width, 44);
    self.searchController.searchBar.frame = rect;
    [self.searchController.searchBar setBackgroundImage:[UIImage new]];
    self.searchController.searchBar.barTintColor = MH_MAIN_BACKGROUNDCOLOR;
    
//    UITextField *txfSearchField = [self.searchController.searchBar valueForKey:@"_searchField"];
//    [txfSearchField setBackgroundColor:RGBA(237, 238, 239, 1)];
    //    self.tableView.tableHeaderView = self.searchController.searchBar;
    /// 插入到下层
    [self.tableView.tableHeaderView sendSubviewToBack:self.searchController.searchBar];
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

@end
